package com.example.writting.ui.words.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.writting.R
import com.example.writting.model.MindMapNode

class MindMapAdapter : RecyclerView.Adapter<MindMapAdapter.MindMapViewHolder>() {
    private var mindMapData: List<MindMapNode> = emptyList()

    fun updateMindMap(data: MindMapNode) {
        mindMapData = if (data.children.isNotEmpty()) data.children else listOf(data)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MindMapViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_mindmap_node, parent, false)
        return MindMapViewHolder(view)
    }

    override fun onBindViewHolder(holder: MindMapViewHolder, position: Int) {
        holder.bind(mindMapData[position])
    }

    override fun getItemCount(): Int = mindMapData.size

    inner class MindMapViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val titleTextView: TextView = itemView.findViewById(R.id.nodeTitle)
        private val childrenRecyclerView: RecyclerView = itemView.findViewById(R.id.childrenRecyclerView)
        private val adapter = MindMapAdapter()

        init {
            childrenRecyclerView.layoutManager = LinearLayoutManager(itemView.context)
            childrenRecyclerView.adapter = adapter
        }

        fun bind(node: MindMapNode) {
            titleTextView.text = node.title
            if (node.children.isNotEmpty()) {
                childrenRecyclerView.visibility = View.VISIBLE
                adapter.updateMindMap(node)
            } else {
                childrenRecyclerView.visibility = View.GONE
            }
        }
    }
} 